package com.posjiajia.user.core.bo;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.posjiajia.commom.utils.enums.OrganTypeEnum;
import com.posjiajia.user.core.dao.OrganDao;
import com.posjiajia.user.core.params.OrganQueryParam;
import com.posjiajia.user.core.po.OrganPo;
import com.posjiajia.user.core.utils.BeanTransferUtil;
import com.posjiajia.user.core.vo.OrganVo;

/**
 * Created by zhenhua.sun on 8/24/16.
 */
@Service
public class OrganBo {

    private static final Logger logger = LoggerFactory.getLogger(OrganBo.class);

    @Autowired
    private OrganDao organDao;

    @Autowired
    private SequenceBo sequenceBo;

    public void insert(OrganVo organVo){
        OrganPo organPo = BeanTransferUtil.transferType(organVo,OrganPo.class);
        organPo.setOrganId(sequenceBo.getNextOrganId());
        organDao.insert(organPo);
    }


    public List<OrganVo> query(OrganQueryParam organQueryParam) {
        OrganPo organPo = BeanTransferUtil.transferType(organQueryParam,OrganPo.class);
        List<OrganPo> poList = organDao.query(organPo);
        List<OrganVo> voList;
        voList = BeanTransferUtil.batchTransferType(poList,OrganVo.class);
        for (OrganVo vo : voList){
            if (vo != null && vo.getParentOrganId() != null){
                OrganPo parent = queryByOrganId(vo.getParentOrganId());
                vo.setParentOrganName(parent == null?"":parent.getName());
            }
        }
        return voList;
    }

    /**
     * 查询
     * @param organId
     * @return
     */
    public OrganPo queryByOrganId(Integer organId) {
        return organDao.queryByOrganId(organId);
    }

	/**
	 * 
	 * @Title get
	 * @Description 根据organId获取组织信息
	 * @param organId
	 * @return
	 *
	 * @author sunhaojie 3113751575@qq.com
	 * @date 2016年11月4日 下午11:41:43
	 */
	public OrganVo get(int organId) {
		OrganPo organPo = organDao.queryByOrganId(organId);
		OrganVo organVo = new OrganVo(organPo);
		OrganPo parentOrganPo = organDao.queryByOrganId(organPo
				.getParentOrganId());
		organVo.setParentOrganName(parentOrganPo.getName());

		return organVo;
	}

	/**
	 * 
	 * @Title queryTopOrgan
	 * @Description 查询top组织
	 * @param organId
	 * @return
	 *
	 * @author sunhaojie 3113751575@qq.com
	 * @date 2016年11月4日 下午11:15:12
	 */
	public OrganVo queryTopOrgan(int organId) {

		OrganPo organPo = organDao.queryByOrganId(organId);
		if (organPo.getType() == OrganTypeEnum.TOP_ORGAN.type) {
			return new OrganVo(organPo);
		} else {
			return queryTopOrgan(organPo.getParentOrganId());
		}
	}

    /**
     * 更新
     * @param organVo
     */
    public void update(OrganVo organVo) {
        OrganPo organPo = BeanTransferUtil.transferType(organVo,OrganPo.class);
        organDao.update(organPo);
    }
}
